package com.org.litepal.slice.manager;

import com.org.litepal.ResourceTable;
import com.org.litepal.provider.StringItemProvider;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ListContainer;
import ohos.global.resource.RawFileEntry;
import ohos.global.resource.ResourceManager;
import ohos.javax.xml.stream.XMLInputFactory;
import ohos.javax.xml.stream.XMLStreamConstants;
import ohos.javax.xml.stream.XMLStreamException;
import ohos.javax.xml.stream.XMLStreamReader;
import org.litepal.LitePalApplication;
import org.litepal.util.Const;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

public class ModelListAbilitySlice extends AbilitySlice {

    private ArrayList<String> mList = new ArrayList<>();

    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_model_list);
        ListContainer listContainer = (ListContainer) findComponentById(ResourceTable.Id_listModel);

        findXml();
        StringItemProvider itemProvider = new StringItemProvider(mList, this.getContext());
        listContainer.setItemProvider(itemProvider);
        listContainer.setItemClickedListener(new ListContainer.ItemClickedListener() {
            @Override
            public void onItemClicked(ListContainer listContainer, Component component, int i, long l) {
                Intent intentStart = new Intent();
                intentStart.setParam(ModelStrutureAbilitySlice.CLASS_NAME,mList.get(i));
                present(new ModelStrutureAbilitySlice(),intentStart);
            }
        });
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }
    private void findXml(){
        XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
        try {
            XMLStreamReader xmlStreamReader = xmlInputFactory.createXMLStreamReader(getConfigInputStream());

            while (xmlStreamReader.hasNext()){
                int type = xmlStreamReader.next();
                if(type== XMLStreamConstants.START_ELEMENT){
                    if (xmlStreamReader.getLocalName().equals("mapping")){
                        mList.add(xmlStreamReader.getAttributeValue("","class"));
                    }
                }
            }
            xmlStreamReader.close();

        } catch (XMLStreamException | IOException e) {
            e.printStackTrace();
        }
    }
    private InputStream getConfigInputStream() throws IOException {
        ResourceManager resManager = LitePalApplication.getSContext().getResourceManager();
        RawFileEntry rawFileEntry = resManager.getRawFileEntry("resources/rawfile/" + Const.Config.CONFIGURATION_FILE_NAME);
        return rawFileEntry.openRawFile();

    }

}

